package net.xuele.learn.concurrent;

import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.FutureListener;
import org.junit.Test;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: yubo
 * @date: 14:54 2020/4/20
 * @Description: 类描述
 */

public class TestFuture {

    public static void main(String[] args) throws InterruptedException {
        EventExecutorGroup group = new DefaultEventExecutorGroup(4);
        System.out.println("开始:" + System.currentTimeMillis());

        Future<Integer> f = group.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println("开始耗时计算:" + System.currentTimeMillis());
                Thread.sleep(10000);
                System.out.println("结束耗时计算:" + System.currentTimeMillis());
                return 100;
            }
        });

        f.addListener(new FutureListener<Object>() {
            @Override
            public void operationComplete(Future<Object> objectFuture) throws Exception {
                if (objectFuture.isSuccess()) {

                }
                System.out.println("计算结果:" + objectFuture.get());
            }
        });

        System.out.println("结束:" + System.currentTimeMillis());
        // 不让守护线程退出
        new CountDownLatch(1).await();

    }

    @Test
    public void testPatrick() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ExecutorService executor = Executors.newCachedThreadPool();
        TestCallable task = new TestCallable();
        PatrickFutureV2<String> futureTask = new PatrickFutureV2<>(task);
        futureTask.addListener(new net.xuele.learn.concurrent.FutureListener() {
            @Override
            public void onSuccess(Object o) {
                System.out.println("成功了=====> " + o);
                countDownLatch.countDown();
            }

            @Override
            public void onFailure(Exception e) {
                System.out.println("失败了！！！");
                countDownLatch.countDown();
            }
        });
        executor.submit(futureTask);
        executor.shutdown();
        countDownLatch.await();
    }

    class TestCallable implements PatrickCallable<String> {

        @Override
        public String call() throws Exception {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return "ok,go";
        }
    }
}
